/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  finalClothForm
 *  FinalClothForm
 *  final_cloth_form
 */



/***** variables declartion section, begin *****/
var finalClothFormInputMode = wacFormInputMode.add;
var finalClothFormObj = {};
var finalClothFormAuditAction = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        finalClothFormAuditAction = new FinalClothFormAuditAction();

        initFinalClothFormFormDialog();

        initFinalClothFormForm();

        bindFinalClothFormEvents();
    }
);

function bindFinalClothFormEvents()
{
    $("#finalClothFormFormDialog").bind('dialogopen', function(event, ui)
    {
        initFinalClothFormFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.finalClothForm.name);//
    });

    $("#finalClothFormFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#finalClothForm_btnSubmit").bind('click', function (e)
    {
        submitFinalClothFormForm();
    });

    $("#finalClothForm_btnClose").bind('click', function (e)
    {
        $("#finalClothFormFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t17002")
        {
            $("div[aria-labelledby='ui-dialog-title-finalClothFormFormDialog']").remove();
            $("#finalClothFormFormDialog").remove();
        }
    });
}


function initFinalClothFormFormDialog()
{
//    wacDebugLog("initFinalClothFormFormDialog.");
    $("#finalClothFormFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initFinalClothFormForm()
{
    $("#finalClothFormForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#finalClothForm_start_date, #finalClothForm_delivery_date").datepicker();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initFinalClothFormFormData()
{
    wacShowBlockUILoading("#finalClothFormFormDialog");
    $('#finalClothForm_supplier_id, #finalClothForm_production_order_id, #finalClothForm_goods_amount_unit_code, #finalClothForm_piece_length_unit_code, #finalClothForm_wrapper_id').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "finalClothForm/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initFinalClothFormFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initFinalClothFormFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#finalClothForm_goods_amount_unit_code");
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#finalClothForm_piece_length_unit_code");
        }

        for(i=0;i<jsonData['items']['wrapper'].length;i++)
        {
            $('<option value="' + jsonData['items']['wrapper'][i].key +'">' + jsonData['items']['wrapper'][i].value +'</option>').appendTo("#finalClothForm_wrapper_id");
        }
   }

   setupFinalClothFormFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#finalClothFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupFinalClothFormFormDefaultValues(defaultValueObj)
{
    if(finalClothFormInputMode == wacFormInputMode.add)   // use default values
    {
        $("#finalClothForm_id").attr("value", 0);
        $('#finalClothForm_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#finalClothForm_supplier_id').flexbox(BASE_URL + 'factory/GetFinalFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "supplier_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#finalClothForm_goods_amount_unit_code option:[value='"+ defaultValueObj.cloth_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#finalClothForm_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: finalClothFormObj.production_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#finalClothForm_production_order_id_input').val(finalClothFormObj.production_order_code);

        $('#finalClothForm_supplier_id').flexbox(BASE_URL + 'factory/GetFinalFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: finalClothFormObj.supplier_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "supplier_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#finalClothForm_supplier_id_input').val(finalClothFormObj.supplier_name);

        $("#finalClothForm_start_date").attr("value", finalClothFormObj.start_date);
        $("#finalClothForm_delivery_date").attr("value", finalClothFormObj.delivery_date);
        $("#finalClothForm_code").attr("value", finalClothFormObj.code);
        $("#finalClothForm_id").attr("value", finalClothFormObj.id);

        $("#finalClothForm_level").attr("value", finalClothFormObj.level);
        $("#finalClothForm_piece_length").attr("value", finalClothFormObj.piece_length);
        $("#finalClothForm_label_spec").attr("value", finalClothFormObj.label_spec);
        $("#finalClothForm_memo").attr("value", finalClothFormObj.memo);

        $("#finalClothForm_goods_amount_unit_code option:[value='"+ finalClothFormObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#finalClothForm_piece_length_unit_code option:[value='"+ finalClothFormObj.piece_length_unit_code +"']").attr('selected', 'selected');
        $("#finalClothForm_wrapper_id option:[value='"+ finalClothFormObj.wrapper_id +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(finalClothFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("finalClothFormInputMode: " + finalClothFormInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function FinalClothFormAuditAction(){
    this.run = function(orderId){
        finalClothFormAudit(orderId);
    }
}

function finalClothFormAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "final_cloth_form_id" : orderId
    };
//    finalClothFormObj = $("#finalClothFormList").getRowData(orderId);
//    console.log($.dump(finalClothFormObj));

    $.ajax({
        url: BASE_URL + "finalClothForm/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            finalClothFormAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function finalClothFormAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#finalClothFormList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function finalClothFormOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    finalClothFormInputMode = inputMode;

    if(rowid === undefined){
        finalClothFormObj = {};
    }
    else
    {
        finalClothFormObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateFinalClothFormForm()
{
    var validateFlag = true;

    if (!$("#finalClothFormForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    var startDate    = $("#finalClothForm_start_date").datepicker( 'getDate' );
    var deliveryDate = $("#finalClothForm_delivery_date").datepicker( 'getDate' );
    if(deliveryDate <= startDate)
    {
        wacShowTips("发货日期不得早于开始日期!");
        validateFlag = false;
    }

    return validateFlag;
}

function submitFinalClothFormForm()
{
    if(!validateFinalClothFormForm()){
        return;
    }

    wacShowBlockUILoading("#finalClothFormFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(finalClothFormInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "finalClothForm/add";
    }
    else{
        submitUrl = BASE_URL + "finalClothForm/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#finalClothFormForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitFinalClothFormFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitFinalClothFormFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#finalClothFormList").trigger("reloadGrid");
   }

   wacHideBlockUI("#finalClothFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/